;;; +projectile.el --- Initialization and mode setting.

;;; Homepage:
;; https://github.com/bbatsov/projectile

;;; Commentary:
;; Project interaction.

;;; Code:

(use-package projectile
  :ensure
  :hook
  (prog-mode . projectile-mode)
  :bind
  (:map projectile-mode-map
	("M-s p" . projectile-ag))
  :init
  (make-directory (expand-file-name "projectile" spruce-cache-truedirectory) :PARENTS)

  (setq enable-local-variables :all
	projectile-known-projects-file (expand-file-name "projectile/projects" spruce-cache-truedirectory)
	projectile-cache-file (expand-file-name "projectile/cache" spruce-cache-truedirectory)
	projectile-switch-project-action 'neotree-projectile-action
	projectile-track-known-projects-automatically nil)

  :config
  (defcustom projectile-project-dir-local-variables-file (expand-file-name "projectile/dir-locals.el" spruce-third-truedirectory)
    "Absolute path to the script with local variables."
    :group 'projectile
    :type 'string)

  (defun projectile-project-dir-local-variables-install (path)
    "Copy `projectile-project-dir-local-variables-file' to the project directory."
    (interactive
     (list
      (read-file-name "Path: "
		      (projectile-project-root)
		      ".dir-locals.el"
		      t
		      ".dir-locals.el")))
    (when (file-exists-p projectile-project-dir-local-variables-file)
      (copy-file projectile-project-dir-local-variables-file path :OK-IF-ALREADY-EXISTS)
      (let ((default-directory (projectile-project-root)))
	(hack-dir-local-variables-non-file-buffer))
      (find-file-existing path)))

  (defun projectile-project-execute-action (action)
    "Execute action on projects from `projectile-project-actions'."
    (projectile-project-dir-local-variables-reload)
    (interactive
     (list
      (completing-read "Action: "
		       (mapcar (lambda (action)
				 (car action))
			       (cdr (assoc projectile-project-major-mode projectile-project-actions)))
		       nil :REQUIRE-MATCH)))
    (let ((default-directory (projectile-project-root)))
      (compile (cdr (assoc action (cdr (assoc projectile-project-major-mode projectile-project-actions)))))))

  (defun projectile-project-dir-local-variables-reload ()
    "Reload dir locals in project directory."
    (interactive)
    (let ((default-directory (projectile-project-root)))
      (hack-dir-local-variables-non-file-buffer))))

(provide '+projectile)

;;; +projectile.el ends here
